/**
 * @description vite自定义插件 - 创建前端项目版本 + 校验 + 提示
 * @author 叶花弈
 * @lastModify 2024-08-12
 */

export default () => {
  return {
    name: "vite-plugin-webVersion",
    transform(code, id) {
      // 往main.js里面注入JS代码
      if (id.endsWith("main.js")) {
        const script = `
          const debounce = (callBack, delay = 500, immediate = false) => {
            let timer = null;
            return function (...args) {
              clearTimeout(timer);
              if (immediate) {
                const runNow = !timer;
                timer = setTimeout(() => {
                timer = null;
              }, delay);
              if (runNow) {
                  callBack.apply(this, args);
                }
              } else {
                timer = setTimeout(() => {
                  callBack.apply(this, args);
                }, delay);
              }
            };
          };
          const checkWebVersion = debounce(async () => {
            try {
              const url = window.location.origin + window.location.pathname;
              const res = await fetch(url + '?v=' + new Date().getTime());
              const HTMLString = await res.text();
              if (window._HTMLString !== HTMLString) {
                ElMessage({
                  showClose: true,
                  message: "系统已有更新, 请刷新页面!",
                  type: "warning",
                  duration: 0,
                });
              }
            } catch (error) {
              throw new Error(error);
            }
          });
          // 获取当前浏览器html文件 + 绑定校验
          fetch(window.location.origin + window.location.pathname).then(async res => {
            window._HTMLString = await res.text();
            // 点击事件绑定校验
            window.addEventListener("click", () => {
              checkWebVersion();
            });
            // XHR请求绑定校验
            const oldOpen = XMLHttpRequest.prototype.open;
            XMLHttpRequest.prototype.open = function (method, url) {
              checkWebVersion();
              oldOpen.apply(this, arguments);
            };
            // 立即校验一次
            checkWebVersion()
          })
        `;
        return `${code}\n${script}`;
      }
    },
  };
};
